﻿using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.API.ViewModel;
using ConfigInfoWebPlatform.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 流程数据解析
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class DataSourceController : ControllerBase
    {
        /// <summary>
        /// 数据源列表
        /// </summary>
        [HttpGet("index")]
        public JsonResult Index(int page,int limit,string caseTypeCode,string code,string name)
        {
            //SetDataSource();
            DAL_DataSource sourceDal = new DAL_DataSource();
            List<DataSource> re = new List<DataSource>();
            Expression<Func<DataSource, bool>> sourceWhere = null;

            if(!string.IsNullOrWhiteSpace(caseTypeCode))
            {
                sourceWhere = sourceWhere.And(x => x.CaseTypeCode==caseTypeCode);
            }

            if (!string.IsNullOrWhiteSpace(code))
            {
                sourceWhere = sourceWhere.And(x => x.Code.Contains(code));
            }
            if (!string.IsNullOrWhiteSpace(name))
            {
                sourceWhere = sourceWhere.And(x => x.Name.Contains(name));
            }
            var sourceList = sourceDal.GetDataSourceByFilter(sourceWhere);

            if (sourceList != null && sourceList.Any())
            {
                re = sourceList.Skip((page - 1) * limit).Take(limit).ToList();
            }
            return new JsonResult(new { code = 0, msg = "成功", count = sourceList.Count, data = re });
        }

        /// <summary>
        /// 添加数据源
        /// </summary>
        [HttpPost("adddatasource")]
        public IActionResult AddDataSource(AddDataSourceModel model)
        {
            DAL_DataSource sourceDal = new DAL_DataSource();
            if(model.CaseTypes!=null && model.CaseTypes.Any())
            {
                foreach (var caseType in model.CaseTypes)
                {
                    DataSource source = sourceDal.GetDataSourceByCode(model.Code.ToLower(), caseType.CaseTypeCode);
                    if (source == null)
                    {
                        source = new DataSource();
                        source.Id = System.Guid.NewGuid().ToString("N");
                        source.CaseTypeCode = caseType.CaseTypeCode;
                        source.CaseTypeName = caseType.CaseTypeName;
                        source.Code = model.Code.ToLower();
                        source.Name = model.Name;
                        var result = sourceDal.InsertDataSource(source);
                    }
                }
            }
            return new JsonResult(new { code = 1, msg = $"添加成功" });
        }

        /// <summary>
        /// 获取案件树
        /// </summary>
        [HttpGet("getcasetree")]
        public IActionResult GetCaseTree()
        {
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            Expression<Func<ProgramNavicat, bool>> navWhere = null;
            navWhere = navWhere.And(x => x.Directory.StartsWith(@"config/processconfig/analysisprocessconfig") &&(x.Level == 2 || x.Level==3));
            var caseNavs = navicatDal.GetNavicatByFilter(navWhere);
            var caseGroup = caseNavs.Where(x=>x.Level==2)
                                    .Select(x => new CaseTreeModel()
                                     {
                                         Id = x.Id,
                                         Code= Path.GetFileNameWithoutExtension(x.Directory),
                                         Name = x.Name.Replace("流程",""),
                                     }).ToList();
            foreach (var item in caseGroup)
            {
                GetCaseChilder(caseNavs, item);
            }
            return new JsonResult(new
            {
                code = 0,
                msg = "success",
                data = caseGroup
            });
        }

        /// <summary>
        /// 获取案件类型数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("getcasetypes")]
        public IActionResult GetCaseTypes() {
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            Expression<Func<ProgramNavicat, bool>> navWhere = null;
            navWhere = navWhere.And(x => x.Directory.StartsWith(@"config/processconfig/analysisprocessconfig") &&  x.Level == 3);
            var caseNavs = navicatDal.GetNavicatByFilter(navWhere);
            var caseTypes = caseNavs.Select(x => new CaseTypeModel()
                                    {
                                        CaseTypeCode = Path.GetFileNameWithoutExtension(x.Directory),
                                        CaseTypeName = x.Name.Replace("流程", ""),
                                    }).ToList();
            return new JsonResult(new { code = 1, msg = "成功", data = caseTypes });
        }

        /// <summary>
        /// 根据Id获取数据源信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdatasourcebyid")]
        public IActionResult GetDataSourceById(string id)
        {
            DAL_DataSource dataSourceDal = new DAL_DataSource();
            var dataSource = dataSourceDal.GetDataSourceById(id);
            return new JsonResult(new { code = 1, msg = "成功", data = dataSource });
        }

        /// <summary>
        /// 修改数据源信息
        /// </summary>
        [HttpPost("editdatasource")]
        public IActionResult EditDataSource(DataSource model)
        {
            DAL_DataSource sourceDal = new DAL_DataSource();
            DataSource source = sourceDal.GetDataSourceByCode(model.Code.ToLower(), model.CaseTypeCode);
            source.Name = model.Name;
            var result = sourceDal.UpdateDataSource(source);
            return new JsonResult(new { code = result? 1:0, msg =result?"保存成功":"保存失败" });
        }

        /// <summary>
        /// 删除组织信息
        /// </summary>
        [HttpPost("deletedatasource")]
        public IActionResult DeleteDataSource(string id)
        {
            DAL_DataSource sourceDal = new DAL_DataSource();
            int resultCode = 0;
            string resultMsg = "删除失败";
            var source = sourceDal.GetDataSourceById(id);
            if (source != null && !string.IsNullOrWhiteSpace(source.Id))
            {
                var delResult = sourceDal.DeleteDataSource(id);
                if (delResult)
                {
                    resultCode = 1;
                    resultMsg = "删除成功";
                }
                    
            }
            else
                resultMsg = "该数据源不存在或已被删除";
            return new JsonResult(new
            {
                code = resultCode,
                msg = resultMsg
            });
        }

        /// <summary>
        /// 加载案件子级数据
        /// </summary>
        private void GetCaseChilder(List<ProgramNavicat> allNavs, CaseTreeModel parent)
        {
            if (parent != null)
            {
                var childers = allNavs.Where(x => x.ParentId == parent.Id).ToList();
                if (childers.Any())
                {
                    parent.Childrens = childers.Select(x => new CaseTreeModel()
                    {
                        Id = x.Id,
                        Name = x.Name.Replace("流程", ""),
                        Code = Path.GetFileNameWithoutExtension(x.Directory),
                    }).ToList();
                    foreach (var nav in parent.Childrens)
                    {
                        GetCaseChilder(allNavs, nav);
                    }
                }
            }
        }

        /// <summary>
        /// 写入数据源
        /// </summary>
        /// <returns></returns>
        [HttpGet("setdatasource")]
        public IActionResult SetDataSource()
        {
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_DataSource sourceDal = new DAL_DataSource();
            Expression<Func<ConfigFiles, bool>> configWhere = null;
            configWhere = configWhere.And(x => x.Path.StartsWith(@"config/processconfig/analysisprocessconfig") && x.Level == 3);
            var sourceConfigs = configFileDal.GetConfigFilesByFilter(configWhere);
            if(sourceConfigs!=null && sourceConfigs.Any())
            {
                foreach (var config in sourceConfigs)
                {
                    var caseTypeCode = Path.GetFileNameWithoutExtension(config.parentPath);
                    var sourceCode = config.name.ToLower();
                    DataSource source = new DataSource();
                    source.Id = System.Guid.NewGuid().ToString("N");
                    source.CaseTypeCode = caseTypeCode;
                    source.Code = sourceCode;
                    sourceDal.InsertDataSource(source);
                }
            }

            string filepath = Path.Combine(System.Environment.CurrentDirectory, "CaseTypeWrit.json");
            string jsonStr = System.IO.File.ReadAllText(filepath);
            Expression<Func<DataSource, bool>> sourceWhere = null;
            var allSource = sourceDal.GetDataSourceByFilter(sourceWhere);

            // 获取json里面当前案件类型的文书列表
            List<WritsItem> writTypes = new List<WritsItem>();
            WRoot writList = System.Text.Json.JsonSerializer.Deserialize<WRoot>(jsonStr);

            foreach (var writItem in writList.CaseTypeWrit)
            {
                // 判断是否有当前文书的目录，没有就创建
                writTypes = writItem.writs;
                foreach (WritsItem item in writTypes)
                {
                    DataSource source = sourceDal.GetDataSourceByCode(item.code.ToLower(), writItem.code);
                    if(source!=null)
                    {
                        source.CaseTypeName = writItem.caseTypeZh;
                        source.Name = item.name;
                        sourceDal.UpdateDataSource(source);
                    }
                    else
                    {
                        source = new DataSource();
                        source.Id = System.Guid.NewGuid().ToString("N");
                        source.CaseTypeCode = writItem.code;
                        source.Code = item.code.ToLower();
                        source.CaseTypeName = writItem.caseTypeZh;
                        source.Name = item.name.ToLower().Replace($"-{item.code}","");
                        sourceDal.InsertDataSource(source);
                    }


                }
            }
            return Ok("success");
        }
    }
}
